package com.haierCamera.customapplication.ui.login;

import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;

import com.google.gson.Gson;
import com.haierCamera.customapplication.BaseActivity;
import com.haierCamera.customapplication.Constants;
import com.haierCamera.customapplication.R;
import com.haierCamera.customapplication.api.repo.RegisterRepo;
import com.haierCamera.customapplication.api.vo.GetUserInfoResponse;
import com.haierCamera.customapplication.api.vo.LoginResponse;
import com.haierCamera.customapplication.api.vo.TXOauth;
import com.haierCamera.customapplication.databinding.HzklActivityLoginWelcomeBinding;
import com.haierCamera.customapplication.ui.MainActivity;
import com.haierCamera.customapplication.utils.AppManager;
import com.haierCamera.customapplication.utils.SharedPreferencesUtils;
import com.haierCamera.customapplication.utils.android.HttpErrorProcess;
import com.haierCamera.customapplication.utils.android.SystemUIHelper;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.json.JSONException;
import org.json.JSONObject;

import javax.inject.Inject;

import dagger.Lazy;

public class HZKLLoginWelcomeActivity extends BaseActivity {
    private HzklActivityLoginWelcomeBinding binding;
    @Inject
    RegisterRepo repo;
    private IWXAPI api;
    @Inject
    Lazy<HttpErrorProcess> errorProcessLazy;
    private static final String PWD_MATCH = "^1+[3,4,5,6,7,8,9]+\\d{9}";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SystemUIHelper.setFullWindowNew(getWindow());
        binding = DataBindingUtil.setContentView(this, R.layout.hzkl_activity_login_welcome);
        initData();
    }

    private void initData() {
        api = WXAPIFactory.createWXAPI(this, Constants.WeiXiID, false);
        api.registerApp(Constants.WeiXiID);
        binding.loginWX.setOnClickListener(view -> requestWeiXi());
        binding.registerBtn.setOnClickListener(view -> startActivity(new Intent(HZKLLoginWelcomeActivity.this, HZKLRegisterActivity.class)));
        binding.loginBtn.setOnClickListener(view -> startActivity(new Intent(HZKLLoginWelcomeActivity.this, HZKLLoginActivity.class)));
    }

    private void requestWeiXi() {
        if (!api.isWXAppInstalled()) {
            Toast.makeText(HZKLLoginWelcomeActivity.this, "您的设备未安装微信客户端", Toast.LENGTH_SHORT).show();
        } else {
            final SendAuth.Req req = new SendAuth.Req();
            req.scope = "snsapi_userinfo";
            req.state = "wechat_sdk_demo_test";
            api.sendReq(req);

        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        String info = SharedPreferencesUtils.getString(Constants.WeiXi_USER_INFO, "");
        String openId = SharedPreferencesUtils.getString(Constants.WeiXi_USER_OPENID, "");
        if (TextUtils.isEmpty(info)) {
            return;
        }
        //showLoadingDialog();
        try {
            JSONObject jsonObject = new JSONObject(info);
            String nickname = jsonObject.getString("nickname");
            String headimgurl = jsonObject.getString("headimgurl");
            registerWX(nickname, headimgurl, openId);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        SharedPreferencesUtils.removeSync(Constants.WeiXi_USER_INFO);
        SharedPreferencesUtils.removeSync(Constants.WeiXi_USER_OPENID);
    }


    private void getUser() {
        repo.getUserInfo().observe(this, getUserInfoResource -> {
            switch (getUserInfoResource.status) {
                case LOADING:
                    break;
                case ERROR:
                    break;
                case SUCCESS:
                    GetUserInfoResponse data = getUserInfoResource.data;
                    assert data != null;
                    if (TextUtils.isEmpty(data.nickName)) {
//                        binding.phone.setText(data.mobile);
                        SharedPreferencesUtils.saveString(Constants.SP_USER_PHONE, data.mobile);
                    } else {
//                        binding.phone.setText(data.nickName);
                        SharedPreferencesUtils.saveString(Constants.SP_USER_PHONE, data.nickName);
                    }
                    SharedPreferencesUtils.saveString(Constants.SP_USER_HEAD_URL, data.headUrl);

                    startActivity(new Intent(HZKLLoginWelcomeActivity.this, MainActivity.class));
                    finish();
                    AppManager.getAppManager().finishAllActivity();
//                    Glide.with(this).load(data.headUrl).apply(new RequestOptions().circleCrop()).into(binding.userIcon);
                    break;
            }
        });
    }

    private void registerWX(String nickname, String headimgurl, String openId) {
        repo.oauth("0", openId, nickname, headimgurl).observe(this, txOauthResource -> {
            switch (txOauthResource.status) {
                case LOADING:
                    break;
                case ERROR:
                    errorProcessLazy.get().process(txOauthResource);
                    dismissLoadingDialog();
                    break;
                case SUCCESS:
                    TXOauth data = txOauthResource.data;
                    //是否绑定账户 true=需要绑定 false=不需要绑定并取token字段
                    new Handler().postDelayed(() -> {
                        dismissLoadingDialog();
                        assert data != null;
                        if (data.flag) {
                            startActivityForResult(new Intent(HZKLLoginWelcomeActivity.this, HZKLWXphoneActivity.class).putExtra("openId", openId), 100);
                        } else {
                            getUser();
                            SharedPreferencesUtils.saveString(Constants.SP_USER_TOKEN, data.token);
                            //startActivity(new Intent(HZKLLoginActivity.this, MainActivity.class));
                        }
                    }, 1000);
                    break;
                default:
                    break;
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 100 && resultCode == RESULT_OK) {
            finish();
        }
    }
}
